<?php

namespace App\Http\Controllers\Api;

use App\Base\BaseController;
use App\Helper\AlgorithmHelper;
use App\Models\Role\User;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Exceptions\JWTException;
//use Tymon\JWTAuth\JWTAuth;
use Tymon\JWTAuth\Facades\JWTAuth;

//use Illuminate\Routing\Controller as BaseController;

class UserController extends BaseController
{
    public $loginAfterSignUp = true;

    public function register(Request $request)
    {
        $user = new User();
        $user->name = $request->name;
        $user->email = $request->email;
        $user->password = bcrypt($request->password);
        $user->save();

        if ($this->loginAfterSignUp) {
            return $this->login($request);
        }

        return response()->json([
            'success' => true,
            'data' => $user
        ], 200);
    }

    public function login(Request $request)
    {
        $input = $request->only('mobile', 'password');
        $jwt_token = null;

        $user = User::where('mobile','=',$input['mobile'])->first();
        if (!$user)
        {
            return response()->json([
                'success' => false,
                'message' => 'Invalid Email or Password',
            ], 401);
        }

        $token=JWTAuth::fromUser($user);//生成token
//        if (!$jwt_token = JWTAuth::attempt($input)) {
//            return response()->json([
//                'success' => false,
//                'message' => 'Invalid Email or Password',
//            ], 401);
//        }

        return response()->json([
            'success' => true,
            'token' => $token,
        ]);
    }

    public function logout(Request $request)
    {
        $this->validate($request, [
            'token' => 'required'
        ]);

        try {
            JWTAuth::invalidate($request->token);

            return response()->json([
                'success' => true,
                'message' => 'User logged out successfully'
            ]);
        } catch (JWTException $exception) {
            return response()->json([
                'success' => false,
                'message' => 'Sorry, the user cannot be logged out'
            ], 500);
        }
    }

    public function getAuthUser(Request $request)
    {
        $this->validate($request, [
            'token' => 'required'
        ]);

        $user = JWTAuth::authenticate($request->token);

        return response()->json(['user' => $user]);
    }

    public function image()
    {
        $img = public_path("favicon.ico");

        $fp= fopen($img, 'rb');

        $content = fread($fp, filesize($img));//二进制数据
        dd($content);
    }
}
